package com.hoperun.nocserver.common.conf;

import java.io.IOException;

import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hoperun.nocserver.common.entity.Encrypt;
import com.hoperun.nocserver.common.entity.Request;
import com.hoperun.nocserver.common.entity.Response;
import com.hoperun.nocserver.common.utils.JsonUtil;
import com.hoperun.nocserver.modules.user.service.SysUserService;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

/**
 * rabbitmq rpc通道配置
 * 
 * @author zhu_longxiang
 *
 */
@Component
public class RabbitMqRpcServer {

	private static final Log LOGGER = Logs.get();

	@Autowired
	private ConnectionFactory connectionFactory;

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private Encrypt encrypt;

	/**
	 * rpc监听
	 * 
	 * @param queue
	 *            队列名称
	 */
	public void onMessageReceiver(final String queue) {
		Connection connection = null;
		try {

			connection = connectionFactory.createConnection();

			final Channel channel = connection.createChannel(false);

			channel.queueDeclare(queue, false, false, false, null);

			channel.basicQos(1);

			LOGGER.infof("队列[%s]等待RPC请求", queue);

			Consumer consumer = new DefaultConsumer(channel) {
				@Override
				public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
						byte[] body) throws IOException {
					AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder()
							.correlationId(properties.getCorrelationId()).build();

					// 定义具体的返回信息
					String response = "";

					try {
						String message = new String(body, "UTF-8");
						LOGGER.debugf("mq-rpc通道队列[%s]接收消息为: %s", queue, message);
						// 业务操作
						dealWithMessage(message);
					} catch (RuntimeException e) {
						LOGGER.error("mq-rpc通道处理请求消息错误！", e);
					} finally {
						channel.basicPublish("", properties.getReplyTo(), replyProps, response.getBytes("UTF-8"));

						channel.basicAck(envelope.getDeliveryTag(), false);

						synchronized (this) {
							this.notify();
						}
					}
				}
			};

			channel.basicConsume(queue, false, consumer);

			while (true) {
				synchronized (consumer) {
					try {
						consumer.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			LOGGER.error("mq-rpc通道操作错误！", e);
		} finally {
			try {
				if (connection != null)
					connection.close();
			} catch (Exception e) {
				LOGGER.error("关闭mq连接失败！", e);
			}
		}
	}

	private String dealWithMessage(String message) {
		// 解unicode
		// 解码
		Response response = null;
		Request request = JsonUtil.toBean(message, Request.class);
		String method = request.getMethod();
		if ("login".equalsIgnoreCase(method)) {
			response = sysUserService.login(request);
		}

		return JsonUtil.toJSONString(response);
	}

	private String strDec(String message) {
		return null;
	}

}
